package com.genokon.util;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.Properties;

/**
 * @author by baichaoda
 * @date 2020/9/22 15:07
 */
public class ResponseFactory extends DefaultPropertySourceFactory {
    private static final String YML_EXT = ".yml";
    private static final String YAML_EXT = ".yaml";

    @NonNull
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (sourceName.endsWith(YML_EXT) || sourceName.endsWith(YAML_EXT)) {
//            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
//            Resource[] resources = resourcePatternResolver.getResources(sourceName);
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            Properties propertiesFromYaml = factory.getObject();
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }
}
